/**
 *
 *      ___                       ___
 *     /\  \          ___        /\  \
 *    /::\  \        /\  \      /::\  \
 *   /:/\:\  \       \:\  \    /:/\ \  \
 *  /:/  \:\  \      /::\__\  _\:\~\ \  \
 * /:/__/ \:\__\  __/:/\/__/ /\ \:\ \ \__\
 * \:\  \  \/__/ /\/:/  /    \:\ \:\ \/__/
 *  \:\  \       \::/__/      \:\ \:\__\
 *   \:\  \       \:\__\       \:\/:/  /
 *    \:\__\       \/__/        \::/  /
 *     \/__/                     \/__/
 *
 * CIS - Clang Indexing Service is a Project Manager & Source code indexing service
 * created so as to simplify the indexing of C/C++ based source code which use
 * standardized build mechanisms.
 *
 **/

#include "../includes/projectdirectory.hxx"

using namespace cis;

typedef Project::ProjectPtr ProjectPtr;

ProjectDirectory& ProjectDirectory::instance()
{
    static Poco::SingletonHolder<ProjectDirectory> pd;
    return *pd.get();
}

bool ProjectDirectory::hasProject(const std::string& name)
{
    Poco::ScopedLock<Poco::Mutex> lock(mtx);
    return pHasProject(name);
}

ProjectPtr ProjectDirectory::createProject(const std::string& name, const std::string& mf, const std::string& makeparams)
{
    Poco::ScopedLock<Poco::Mutex> lock(mtx);
    HashMap::Iterator iter = projMap.find(name);
    if (iter != projMap.end()) {
        throw cis::Exception("Project with name " + name + " already exists!");
    } else {
        return pCreateProject(name, mf, makeparams);
    }
}

ProjectPtr ProjectDirectory::getProject(const std::string& name)
{
    Poco::ScopedLock<Poco::Mutex> lock(mtx);
    HashMap::Iterator iter = projMap.find(name);
    if (iter != projMap.end()) {
        return iter->second;
    } else
        throw cis::Exception("project not found");
}

void ProjectDirectory::removeProject(const std::string& name)
{
    Poco::ScopedLock<Poco::Mutex> lock(mtx);
    HashMap::Iterator iter = projMap.find(name);
    if (iter != projMap.end()) {
        projMap.erase(iter);
    } else
        throw cis::Exception("project not found");
}

ProjectPtr ProjectDirectory::pCreateProject(const std::string& name, const std::string& mf, const std::string& makeparams)
{
    ProjectPtr pptr(new Project(name, mf, makeparams));
    projMap[name] = pptr;
    return pptr;
}

bool ProjectDirectory::pHasProject(const std::string& name)
{
    if (projMap.find(name) != projMap.end())
        return true;
    return false;
}